﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using API;
using DB;

namespace ProductManage
{
    public partial class FormProducts : Form
    {
        private ProductsDb _db = ProductsDb.DbMysql;
        private List<Product> listProduct;
        private List<Product> listProductUpdate = new List<Product>(); 
        private List<string> listAttributr = new List<string>(){"Type", "Size", "Weight", "Color", 
            "Themes","Stones", "Metals",  "Materials", "Price", "PriceSale", "PricePurchase",}; 
        public FormProducts()
        {
            InitializeComponent();
            this.Type.Items.AddRange("", "Charms", "Clips", "Pendants", "Spacers", "SafetyChains", "SnakeChain");
            dicAttributr.Add("Type", new List<string>() { "Charms", "Clips", "Pendants", "Spacers", "SafetyChains", "SnakeChain" });
            this.Stones.Items.AddRange("", "With Stone", "Without Stone", "Pavé");
            dicAttributr.Add("Stones", new List<string>() { "With Stone", "Without Stone", "Pavé" });
            this.Metals.Items.AddRange("", "Silver", "Gold", "Two Tone");
            dicAttributr.Add("Metals", new List<string>() { "Silver", "Gold", "Two Tone" });
            this.Themes.Items.AddRange("", "Alphabet & Numbers", "Animals", "Cause & Awareness", "Decorative", "Fairy Tale",
                "Family and Friends", "Floral", "Glamour", "Glass", "Hobbies", "Love", "Nature", "Occasions", "Occupation", "Symbols", "Travel");
            dicAttributr.Add("Themes", new List<string>() { "Alphabet & Numbers", "Animals", "Cause & Awareness", "Decorative", "Fairy Tale",
                "Family and Friends", "Floral", "Glamour", "Glass", "Hobbies", "Love", "Nature", "Occasions", "Occupation", "Symbols", "Travel" });
            this.Materials.Items.AddRange("", "Sterling Silver", "Enamel", "Glass", "Pearl");
            dicAttributr.Add("Materials", new List<string>() { "Sterling Silver", "Enamel", "Glass", "Pearl" });
        }

        #region productlist
        private void buttonLoadData_Click(object sender, EventArgs e)
        {
            listProduct = _db.GetAllProducts();
            this.textBoxPageIndex.Text = "0";
        }

        private List<Product> GetProductListBySearch(List<Product> list,string strKeywords)
        {
            strKeywords = strKeywords.Trim(' ', '\r', '\n', ',');
            if (strKeywords == "") return list;
            var listRtn = new List<Product>();
            if (listAttributr.Contains(strKeywords))
            {
                switch (strKeywords)
                {
                    case "Type":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Type) select p).ToList();
                        break;
                    case "Size":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Size) select p).ToList();
                        break;
                    case "Weight":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Weight) select p).ToList();
                        break;
                    case "Color":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Color) select p).ToList();
                        break;
                    case "Themes":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Theme) select p).ToList();
                        break;
                    case "Stones":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Stone) select p).ToList();
                        break;
                    case "Metals":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Metals) select p).ToList();
                        break;
                    case "Materials":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Material) select p).ToList();
                        break;
                    case "Price":
                        listRtn = (from p in list where p.Price == 0 select p).ToList();
                        break;
                    case "PriceSale":
                        listRtn = (from p in list where p.PriceSale == 0 select p).ToList();
                        break;
                    case "PricePurchase":
                        listRtn = (from p in list where p.PricePurchase == 0 select p).ToList();
                        break;
                    case "Feature":
                        listRtn = (from p in list where string.IsNullOrEmpty(p.Feature) select p).ToList();
                        break;
                }
            }
            else
            {
                var keywords = strKeywords.Split(',', ' ', '\r', '\n');
                if (keywords.Count() == 1)
                    listRtn = (from p in list where p.SKU.Contains(keywords[0]) select p).ToList();
                else
                    listRtn = (from p in list where keywords.Contains(p.SKU) select p).ToList();

            }

            return listRtn;
        }
        private void ShowProduct(int page, int pageTotal)
        {
            if (listProduct == null) listProduct = _db.GetAllProducts();
            var list = GetProductListBySearch(listProduct,this.textBoxSearch.Text).Skip(pageTotal * page).Take(pageTotal).ToList();
            dataGridViewProductList.Rows.Clear();
            this.imageList1.Images.Clear();
            foreach (var p in list)
            {
                Image image= new Bitmap(1,1);
                var images = ProductImageApi.GetImages(p.SKU);
                if(images.Count() != 0)
                    image = images[0];
                this.imageList1.Images.Add(p.SKU, image);
                var i = dataGridViewProductList.Rows.Add(new object[] { false,this.imageList1.Images[p.SKU], p.SKU,p.Type,p.Size,p.Weight,p.Color,p.Theme
                    ,p.Stone,p.Metals,p.Material,p.Price,p.PriceSale,p.PricePurchase,p.Feature });
                dataGridViewProductList.Rows[i].Tag = p;
            }
        }

        private void buttonPre_Click(object sender, EventArgs e)
        {
            int i = Convert.ToInt32(this.textBoxPageIndex.Text) -1 ;
            if (i < 0) i = 0;
            this.textBoxPageIndex.Text = i.ToString();
        }

        private void buttonNex_Click(object sender, EventArgs e)
        {
            int i = Convert.ToInt32(this.textBoxPageIndex.Text) + 1;
            if (i > listProduct.Count()) i = listProduct.Count();
            this.textBoxPageIndex.Text = i.ToString();
        }

        private void textBoxPageIndex_TextChanged(object sender, EventArgs e)
        {
            ShowProduct(Convert.ToInt32(this.textBoxPageIndex.Text), Convert.ToInt32(this.textBoxPageTotal.Text));
        }

        private void textBoxPageTotal_TextChanged(object sender, EventArgs e)
        {
            ShowProduct(Convert.ToInt32(this.textBoxPageIndex.Text), Convert.ToInt32(this.textBoxPageTotal.Text));
        }
        #endregion

        #region product
        #region Detail
        private void textBoxBixEditer_TextChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in this.dataGridViewProductList.Rows)
            {
                if ((bool)row.Cells[0].Value == false) continue;

                var selectProduct = row.Tag as Product;
                if (selectProduct == null) return;
                #region get newdata

                string strAttributr = this.textBoxBoxEditer.Tag.ToString();
                row.Cells[strAttributr].Value = this.textBoxBoxEditer.Text;
                if (strAttributr == "Type")
                {
                    #region Type
                    selectProduct.Type = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Feature")
                {
                    #region Feature
                    selectProduct.Feature = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Size")
                {
                    #region Size
                    selectProduct.Size = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Weight")
                {
                    #region Weight
                    selectProduct.Weight = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Color")
                {
                    #region Color
                    selectProduct.Color = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Themes")
                {
                    #region Themes
                    selectProduct.Theme = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Stones")
                {
                    #region Stones
                    selectProduct.Stone = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Metals")
                {
                    #region Metals
                    selectProduct.Metals = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Materials")
                {
                    #region Materials
                    selectProduct.Material = this.textBoxBoxEditer.Text;
                    #endregion
                }
                else if (strAttributr == "Price")
                {
                    #region Price
                    selectProduct.Price = Convert.ToDecimal(this.textBoxBoxEditer.Text);
                    #endregion
                }
                else if (strAttributr == "PriceSale")
                {
                    #region SalePrice
                    selectProduct.PriceSale = Convert.ToDecimal(this.textBoxBoxEditer.Text);
                    #endregion
                }
                else if (strAttributr == "PricePurchase")
                {
                    #region SalePrice
                    selectProduct.PricePurchase = Convert.ToDecimal(this.textBoxBoxEditer.Text);
                    #endregion
                }

                #endregion

                if (!listProductUpdate.Contains(selectProduct)) listProductUpdate.Add(selectProduct);
            }

        }
        
        private void comboBoxDetail_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.textBoxBoxEditer.Text = this.comboBoxDetail.Text;
        }

        private void dataGridViewProductList_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            SetComboBoxDetail(dataGridViewProductList.Columns[e.ColumnIndex].HeaderText);
            this.textBoxBoxEditer.Tag = dataGridViewProductList.Columns[e.ColumnIndex].Name;
        }
        Dictionary<string, List<string>> dicAttributr = new Dictionary<string, List<string>>();
        private void SetComboBoxDetail(string strAttribute)
        {
            this.comboBoxDetail.SelectedIndexChanged -= comboBoxDetail_SelectedIndexChanged;
            if (dicAttributr.ContainsKey(strAttribute))
            {
                this.comboBoxDetail.DataSource = dicAttributr[strAttribute];
                this.comboBoxDetail.SelectedIndex = 0;
                this.comboBoxDetail.Visible = true;
            }
            else
            {
                this.comboBoxDetail.Visible = false;
            }
            this.comboBoxDetail.SelectedIndexChanged += comboBoxDetail_SelectedIndexChanged;
        }
        #endregion

        #region picture
        private Dictionary<string, Image> dicImage = new Dictionary<string, Image>();
        private void ShowProductPics(Product product)
        {
            this.dicImage.Clear();
            this.imageList1.Images.Clear();
            this.listViewPics.Items.Clear();
            var images = ProductImageApi.GetImages(product.SKU);
            int i = 1;
            foreach (var image in images)
            {
                string key = "pic" + i;
                this.dicImage.Add(key, image);
                this.imageList1.Images.Add(key, image);
                this.listViewPics.Items.Add(key, key);
                i++;
            }
            if (dicImage.Count > 0)
                this.pictureBoxPic.Image = dicImage["pic1"];
            else
                this.pictureBoxPic.Image = null;
        }

        private void listViewPics_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listViewPics.SelectedItems.Count > 0)
                this.pictureBoxPic.Image = dicImage[this.listViewPics.SelectedItems[0].ImageKey];
        }
        #endregion

        private void buttonSave_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listProductUpdate.Count; i++)
            {
                var product = listProductUpdate[i];
                this._db.UpdateProduts(product);
            }
            listProductUpdate.Clear();
        }
        #endregion

        private void dataGridViewProductList_Click(object sender, EventArgs e)
        {
            if (this.dataGridViewProductList.SelectedRows.Count > 0)
                ShowProductPics(this.dataGridViewProductList.SelectedRows[0].Tag as Product);
        }

        private void dataGridViewProductList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 3) return;
            var row = this.dataGridViewProductList.Rows[e.RowIndex];
            var selectProduct = row.Tag as Product;
            if (selectProduct == null) return;
            

            #region get newdata

            string strAttributr = dataGridViewProductList.Columns[e.ColumnIndex].Name;
            if (strAttributr == "Type")
            {
                #region Type
                selectProduct.Type = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Feature")
            {
                #region Feature
                selectProduct.Feature = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Size")
            {
                #region Size
                selectProduct.Size = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Weight")
            {
                #region Weight
                selectProduct.Weight = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Color")
            {
                #region Color
                selectProduct.Color = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Themes")
            {
                #region Themes
                selectProduct.Theme = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Stones")
            {
                #region Stones
                selectProduct.Stone = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Metals")
            {
                #region Metals
                selectProduct.Metals = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Materials")
            {
                #region Materials
                selectProduct.Material = row.Cells[e.ColumnIndex].Value.ToString();
                #endregion
            }
            else if (strAttributr == "Price")
            {
                #region Price
                selectProduct.Price = Convert.ToDecimal(row.Cells[e.ColumnIndex].Value.ToString());
                #endregion
            }
            else if (strAttributr == "PriceSale")
            {
                #region SalePrice
                selectProduct.PriceSale = Convert.ToDecimal(row.Cells[e.ColumnIndex].Value.ToString());
                #endregion
            }
            else if (strAttributr == "PricePurchase")
            {
                #region SalePrice
                selectProduct.PricePurchase = Convert.ToDecimal(row.Cells[e.ColumnIndex].Value.ToString());
                #endregion
            }

            #endregion

            if (!listProductUpdate.Contains(selectProduct)) listProductUpdate.Add(selectProduct);
        }
        
    }
}
